<template>
  <div class="bs-anchor-link">
    <div class="link-text" :class="{active: curHref === href}" @click.stop="handleLink()">
      <slot>
        {{ title }}
      </slot>
    </div>
    <div class="sub-link" v-if="slots['sub-link']">
      <slot name="sub-link"></slot>
    </div>
  </div>
</template>
<script setup lang="ts">
import {inject, onUnmounted} from 'vue'
export type BsAnchorLinkProps = {
  /**锚点链接 */
  href: string
  /**锚点文本内容 */
  title?: string
}

const props = withDefaults(defineProps<BsAnchorLinkProps>(), {
  title: ''
})
const slots = defineSlots<{
  default: any
  'sub-link': any
}>()
/**获取父组件注册的方法**/
const registerEl:any = inject('registerEl')
const removeEl:any = inject('removeEl')
const scrollTo:any = inject('scrollTo')
const curHref:any = inject('curHref')

const handleLink = () => {
  scrollTo(props.href)
}

registerEl(props.href)
onUnmounted(() => {
  removeEl(props.href)
})
</script>
<style lang="scss" scoped>
.bs-anchor-link {
  cursor: pointer;
  color: #8c8c8c;
  .link-text {
    padding: 4px 0;
    line-height: 22px;
    &:hover {
      color: var(--primary-color);
    }
    &.active {
      color: var(--primary-color);
      font-weight: 500;
    }
  }
  .sub-link {
    padding-left: 14px;
  }
}
</style>
